package com.sftz.modules.minapp.homework.service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.SqlManager;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Files;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.upload.TempFile;

import com.sftz.assets.entities.question.HomeworkAnswerInfoEntity;
import com.sftz.assets.entities.question.HomeworkEntity;
import com.sftz.assets.entities.question.HomeworkFileQuestionEntity;
import com.sftz.assets.entities.question.HomeworkQuestionAnswerEntity;
import com.sftz.assets.entities.question.HomeworkQuestionAnswerFileEntity;
import com.sftz.assets.entities.question.HomeworkQuestionEntity;
import com.sftz.assets.enums.AnswerStatusEnum;
import com.sftz.assets.enums.ObjectiveEnum;
import com.sftz.assets.enums.QuestionAnswerResourceTypeEnum;
import com.sftz.assets.enums.QuestionTypeEnum;
import com.sftz.assets.enums.YesOrNoEnum;
import com.sftz.assets.utils.QuestionUtil;
import com.sftz.framework.rersult.MobileResult;
import com.sftz.framework.service.aliyun.AliyunVideoDesc;
import com.sftz.framework.service.aliyun.AliyunVideoUploadService;
import com.sftz.framework.service.qiniu.QiniuDownloadService;
import com.sftz.framework.util.CompareUtil;
import com.sftz.framework.util.WeappHtmlUtil;
import com.sftz.modules.common.dto.FillInStemDto;
import com.sftz.modules.common.service.CourseScoreSettingsService;
import com.sftz.modules.minapp.homework.dto.HomeworkAnswerDto;
import com.sftz.modules.minapp.homework.dto.HomeworkAnswerQuestionDto;
import com.sftz.modules.minapp.homework.dto.HomeworkEntryDto;
import com.sftz.modules.minapp.homework.dto.HomeworkModuleInfoDto;
import com.sftz.modules.minapp.homework.dto.HomeworkObjectiveReviewDto;
import com.sftz.modules.minapp.homework.dto.HomeworkQuestionOptionDto;
import com.sftz.modules.minapp.homework.dto.HomeworkSaveAnswerDto;
import com.sftz.modules.minapp.homework.form.HomeworkAnswerDetailForm;
import com.sftz.modules.minapp.homework.form.HomeworkAnswerFileForm;
import com.sftz.modules.minapp.homework.form.HomeworkCommitForm;
import com.sftz.modules.minapp.homework.form.HomeworkDeleteAnswerFileForm;
import com.sftz.modules.minapp.homework.form.HomeworkEntryForm;
import com.sftz.modules.minapp.homework.form.HomeworkResultForm;
import com.sftz.modules.minapp.homework.form.HomeworkSaveQuestAnswerForm;
import com.sftz.modules.minapp.homework.form.UpdateElapsedTimeForm;
import com.sftz.modules.minapp.user.cache.RedissionUserCache;
import com.uxuexi.core.common.util.BeanUtil;
import com.uxuexi.core.common.util.DateUtil;
import com.uxuexi.core.common.util.Util;
import com.uxuexi.core.db.dao.IDbDao;
import com.uxuexi.core.db.util.DbSqlUtil;

@IocBean
public class HomeworkViewService {

	@Inject
	protected IDbDao dbDao;

	@Inject
	protected SqlManager sqlManager;

	@Inject
	private QiniuDownloadService qiniuUploadService;

	@Inject
	private AliyunVideoUploadService aliyunVideoUploadService;

	@Inject
	protected CourseScoreSettingsService courseScoreSettingsService;

	/**
	 * 查询作业入口页所需数据
	 */
	public Map<String, Object> entry(final HomeworkEntryForm form) {
		String token = form.getToken();
		Integer userId = RedissionUserCache.getUserId(token);

		Integer homeworkId = form.getHomeworkId();

		//1 查询作业的基础信息
		Sql sql = Sqls.create(sqlManager.get("minapp_homework_baseInfo"));
		sql.setParam("userId", userId);
		sql.setParam("isPost", YesOrNoEnum.YES.intKey());
		sql.setParam("studentId", userId);
		sql.setParam("marking", AnswerStatusEnum.marking.intKey());
		sql.setParam("finish", AnswerStatusEnum.finish.intKey());
		sql.setParam("homeworkId", homeworkId);
		List<HomeworkEntryDto> lst = DbSqlUtil.query(dbDao, HomeworkEntryDto.class, sql);
		if (!Util.isEmpty(lst) && lst.size() == 1) {
			HomeworkEntryDto homework = lst.get(0);

			//设置延期时间
			Date postDate = homework.getPostDate();
			if (!Util.isEmpty(postDate)) {
				homework.setEndDate(postDate);
			}

			//2 查询模块信息
			Sql moduleSql = Sqls.create(sqlManager.get("minapp_homework_moduleInfo"));
			moduleSql.setParam("homeworkId", homeworkId);
			List<HomeworkModuleInfoDto> moduleList = DbSqlUtil.query(dbDao, HomeworkModuleInfoDto.class, moduleSql);
			homework.setModuleList(moduleList);

			//3，查询作答记录（不提交就不出现在页面）
			Map<String, Object> rmap = allRecord(form);
			@SuppressWarnings("unchecked")
			List<HomeworkAnswerInfoEntity> allRecords = (List<HomeworkAnswerInfoEntity>) rmap
					.get(MobileResult.DATA_KEY);
			//未提交的
			List<HomeworkAnswerInfoEntity> unsubmitted = new ArrayList<>();
			//已提交的
			List<HomeworkAnswerInfoEntity> submitted = new ArrayList<>();
			if (!Util.isEmpty(allRecords)) {
				for (HomeworkAnswerInfoEntity r : allRecords) {
					Integer stat = r.getStatus();

					String readoverName = "";
					if (null != stat && AnswerStatusEnum.marking.intKey() == stat) {
						readoverName = "已批阅";
					} else {
						readoverName = "未批阅";
					}
					r.setReadoverName(readoverName);

					if (AnswerStatusEnum.uncommit.intKey() == stat || AnswerStatusEnum.start.intKey() == stat) {
						unsubmitted.add(r);
					} else {
						submitted.add(r);
					}
				}
			}

			if (!Util.isEmpty(unsubmitted)) {
				if (unsubmitted.size() > 1) {
					return MobileResult.error("未提交的作答记录最多只能有一条", null);
				} else {
					HomeworkAnswerInfoEntity unsubmit = unsubmitted.get(0);
					//到截止时间才提交
					Date now = DateUtil.nowDate();
					Date endDate = homework.getEndDate();
					if (now.after(endDate)) {
						dbDao.update(HomeworkAnswerInfoEntity.class,
								Chain.make("status", AnswerStatusEnum.finish.intKey()).add("finishTime", endDate),
								Cnd.where("id", "=", unsubmit.getId()));
						//+1
						int answerSize = homework.getAnswerSize() + 1;
						homework.setAnswerSize(answerSize);

						unsubmit.setStatus(AnswerStatusEnum.finish.intKey());
						unsubmit.setFinishTime(endDate);
						submitted.add(unsubmit);
					}
				}
			}

			//设置作答状态
			Date homeworkStartDate = homework.getStartDate();
			Date homeworkEndDate = homework.getEndDate();
			int answerNumber = homework.getAnswerNumber();
			int answerSize = homework.getAnswerSize();
			homework.setStartStatus(QuestionUtil.startStatus(homeworkStartDate, homeworkEndDate, answerNumber,
					answerSize));

			//提交时间倒排
			Collections.sort(submitted, new Comparator<HomeworkAnswerInfoEntity>() {
				@Override
				public int compare(HomeworkAnswerInfoEntity o1, HomeworkAnswerInfoEntity o2) {
					if (o1 == o2) {
						return 0;
					}
					Date o1End = o1.getFinishTime();
					Date o2End = o2.getFinishTime();
					if (o1End.before(o2End)) {
						return -1;
					} else {
						return 1;
					}
				}
			});

			Map<String, Object> obj = new HashMap<>();
			obj.put("homework", homework);
			obj.put("records", submitted);
			return MobileResult.success("SUCCESS", obj);
		} else {
			return MobileResult.error("作业数据错误", null);
		}
	}

	/**
	 * 作答页面
	 */
	public Map<String, Object> answer(final HomeworkEntryForm form) {
		String token = form.getToken();
		Integer userId = RedissionUserCache.getUserId(token);

		Integer homeworkId = form.getHomeworkId();

		//如果作答信息不存在而且没用超过设定的作答次数,则新增一条作答信息
		HomeworkEntity homework = dbDao.fetch(HomeworkEntity.class, Cnd.where("id", "=", homeworkId));
		if (Util.isEmpty(homework)) {
			return MobileResult.error("作业不存在", null);
		}

		//所有作答记录
		List<HomeworkAnswerInfoEntity> answerRecords = dbDao.query(HomeworkAnswerInfoEntity.class,
				Cnd.where("studentId", "=", userId).and("taskId", "=", homeworkId), null);
		//已提交的次数
		int commitCount = 0;
		//未提交的作答记录
		List<HomeworkAnswerInfoEntity> uncommitRecords = new ArrayList<>();
		if (!Util.isEmpty(answerRecords)) {
			for (HomeworkAnswerInfoEntity r : answerRecords) {
				Integer stat = r.getStatus();
				if (AnswerStatusEnum.uncommit.intKey() == stat || AnswerStatusEnum.start.intKey() == stat) {
					uncommitRecords.add(r);
				} else {
					commitCount++;
				}
			}
		}

		HomeworkAnswerInfoEntity currRecord = null;
		if (Util.isEmpty(uncommitRecords)) {
			//新增一条作答记录
			Integer answerNumber = homework.getAnswerNumber();
			if (Util.isEmpty(answerNumber)) {
				return MobileResult.error("作业可作答次数不能为空", null);
			} else {
				if (commitCount >= answerNumber) {
					return MobileResult.error("作业提交次数(" + answerNumber + ")已经用完", null);
				} else {
					currRecord = new HomeworkAnswerInfoEntity();
					currRecord.setStatus(AnswerStatusEnum.start.intKey());
					currRecord.setStudentId(userId);
					currRecord.setTaskId(homeworkId);
					currRecord.setStartTime(DateUtil.nowDate());
					currRecord.setElapsedTime(0);
					currRecord.setObjectScore(0.0d);
					currRecord.setSubjectScore(0.0d);
					currRecord = dbDao.insert(currRecord);
				}
			}
		} else {
			//如果有未提交的答题记录
			if (uncommitRecords.size() > 1) {
				return MobileResult.error("未提交的作答记录最多只能有一条", null);
			} else {
				currRecord = uncommitRecords.get(0);
				//到截止时间就提交
				Date now = DateUtil.nowDate();
				Date endDate = homework.getEndTime();
				if (now.after(endDate)) {
					dbDao.update(HomeworkAnswerInfoEntity.class, Chain.make("status", AnswerStatusEnum.finish.intKey())
							.add("finishTime", endDate), Cnd.where("id", "=", currRecord.getId()));

					currRecord.setStatus(AnswerStatusEnum.finish.intKey());
					currRecord.setFinishTime(endDate);
					return MobileResult.error("作业已过期", null);
				}
			}
		}

		//查询作答页面基本信息
		Sql hSql = Sqls.create(sqlManager.get("minapp_homework_answer_Info"));
		hSql.setParam("studentId", userId);
		hSql.setParam("homeworkId", homeworkId);

		//正在答题或未提交的
		hSql.setParam("start", AnswerStatusEnum.start.intKey());
		hSql.setParam("uncommit", AnswerStatusEnum.uncommit.intKey());
		List<HomeworkAnswerDto> lst = DbSqlUtil.query(dbDao, HomeworkAnswerDto.class, hSql);
		if (!Util.isEmpty(lst) && lst.size() == 1) {
			HomeworkAnswerDto dto = lst.get(0);
			dto.setRecordId(currRecord.getId());

			//2 查询作业的试题信息
			Sql sql = Sqls.create(sqlManager.get("minapp_homework_answer_questionList"));
			sql.setParam("userId", userId);
			sql.setParam("homeworkId", homeworkId);

			//试题集合
			Set<HomeworkAnswerQuestionDto> questSet = new TreeSet<>();
			//准备一个Map存放试题id对应的选项
			Map<Integer, List<HomeworkQuestionOptionDto>> optMap = new HashMap<>();
			List<Record> records = DbSqlUtil.query(dbDao, sql, null);
			if (!Util.isEmpty(records)) {
				for (Record r : records) {
					HomeworkAnswerQuestionDto q = BeanUtil.map2Object(r, HomeworkAnswerQuestionDto.class);
					questSet.add(q);

					HomeworkQuestionOptionDto opt = BeanUtil.map2Object(r, HomeworkQuestionOptionDto.class);
					Integer optQid = opt.getOptQid();
					if (!Util.isEmpty(optQid)) {
						List<HomeworkQuestionOptionDto> optLst = optMap.get(optQid);
						if (Util.isEmpty(optLst)) {
							optLst = new ArrayList<>();
							optLst.add(opt);
							optMap.put(optQid, optLst);
						} else {
							optLst.add(opt);
						}
					}
				}
			}

			//设置试题的选项
			if (!Util.isEmpty(questSet)) {
				final Integer recordId = currRecord.getId();
				questSet.forEach(q -> {
					String stem = q.getStem();

					stem = WeappHtmlUtil.clearHtml(stem, "p");
					if (QuestionTypeEnum.FILLIN.intKey() == q.getQuestionType()) {
						FillInStemDto fd = QuestionUtil.fillInStemReplace(stem, q.getAnswerContent());
						stem = fd.getStem();
						q.setFillList(fd.getFillList());
					}
					q.setStem(stem);

					List<HomeworkQuestionOptionDto> optLst = optMap.get(q.getId());
					if (!Util.isEmpty(optLst)) {
						Collections.sort(optLst, new Comparator<HomeworkQuestionOptionDto>() {
							@Override
							public int compare(HomeworkQuestionOptionDto o1, HomeworkQuestionOptionDto o2) {
								return CompareUtil.safeCompareToGt(o1.getOpt(), o2.getOpt());
							}
						});
						q.setOptLst(optLst);
						q.setOptActive();
					}

					Integer questionType = q.getQuestionType();
					if (!Util.isEmpty(questionType) && QuestionTypeEnum.MATERIALSCIENCE.intKey() == questionType) {
						List<HomeworkFileQuestionEntity> questFiles = dbDao.query(HomeworkFileQuestionEntity.class,
								Cnd.where("questionId", "=", q.getId()), null);
						q.setQuestFiles(questFiles);

						Integer answerId = q.getAnswerId();
						if (!Util.isEmpty(answerId)) {
							List<HomeworkQuestionAnswerFileEntity> answerFiles = dbDao.query(
									HomeworkQuestionAnswerFileEntity.class, Cnd.where("answerId", "=", recordId), null);
							q.setAnswerFiles(answerFiles);
						}
					}
				});
			}

			dto.setQuestList(questSet);
			return MobileResult.success("SUCCESS", dto);
		} else {
			return MobileResult.error("作业数据错误", null);
		}
	}

	/**
	 * 作答详情
	 */
	public Map<String, Object> answerDetail(final HomeworkAnswerDetailForm form) {
		//答题记录id
		Integer recordId = form.getRecordId();

		//查询作答页面基本信息
		Sql hSql = Sqls.create(sqlManager.get("minapp_homework_answerDetail_Info"));
		hSql.setParam("recordId", recordId);

		//正在答题或未提交的
		hSql.setParam("start", AnswerStatusEnum.start.intKey());
		hSql.setParam("uncommit", AnswerStatusEnum.uncommit.intKey());
		List<HomeworkAnswerDto> lst = DbSqlUtil.query(dbDao, HomeworkAnswerDto.class, hSql);
		if (!Util.isEmpty(lst) && lst.size() == 1) {
			HomeworkAnswerDto dto = lst.get(0);

			//2 查询作业的试题信息
			Sql sql = Sqls.create(sqlManager.get("minapp_homework_answerDetail_questionList"));
			sql.setParam("recordId", recordId);

			//试题集合
			Set<HomeworkAnswerQuestionDto> questList = new TreeSet<>();
			//准备一个Map存放试题id对应的选项
			Map<Integer, List<HomeworkQuestionOptionDto>> optMap = new HashMap<>();
			List<Record> records = DbSqlUtil.query(dbDao, sql, null);
			if (!Util.isEmpty(records)) {
				for (Record r : records) {
					HomeworkAnswerQuestionDto q = BeanUtil.map2Object(r, HomeworkAnswerQuestionDto.class);
					questList.add(q);

					HomeworkQuestionOptionDto opt = BeanUtil.map2Object(r, HomeworkQuestionOptionDto.class);
					Integer optQid = opt.getOptQid();
					if (!Util.isEmpty(optQid)) {
						List<HomeworkQuestionOptionDto> optLst = optMap.get(optQid);
						if (Util.isEmpty(optLst)) {
							optLst = new ArrayList<>();
							optLst.add(opt);
							optMap.put(optQid, optLst);
						} else {
							optLst.add(opt);
						}
					}
				}
			}

			//设置试题的属性
			if (!Util.isEmpty(questList)) {
				questList.forEach(q -> {
					List<HomeworkQuestionOptionDto> optLst = optMap.get(q.getId());
					if (!Util.isEmpty(optLst)) {
						Collections.sort(optLst, new Comparator<HomeworkQuestionOptionDto>() {
							@Override
							public int compare(HomeworkQuestionOptionDto o1, HomeworkQuestionOptionDto o2) {
								return CompareUtil.safeCompareToGt(o1.getOpt(), o2.getOpt());
							}
						});
						q.setOptLst(optLst);
					}
					q.setQuestAnswer();

					Integer questionType = q.getQuestionType();
					if (!Util.isEmpty(questionType) && QuestionTypeEnum.MATERIALSCIENCE.intKey() == questionType) {
						List<HomeworkFileQuestionEntity> questFiles = dbDao.query(HomeworkFileQuestionEntity.class,
								Cnd.where("questionId", "=", q.getId()), null);

						List<HomeworkQuestionAnswerFileEntity> answerFiles = dbDao.query(
								HomeworkQuestionAnswerFileEntity.class, Cnd.where("answerId", "=", recordId), null);

						q.setQuestFiles(questFiles);
						q.setAnswerFiles(answerFiles);
					}
				});
			}

			dto.setQuestList(questList);
			return MobileResult.success("SUCCESS", dto);
		} else {
			return MobileResult.error("作业数据错误", null);
		}
	}

	/**
	 * 更新作答时间
	 */
	public Map<String, Object> updateElapsedTime(@Param("..") final UpdateElapsedTimeForm form) {
		Integer recordId = form.getRecordId();
		Integer elapsedTime = form.getElapsedTime();
		dbDao.update(HomeworkAnswerInfoEntity.class, Chain.make("elapsedTime", elapsedTime),
				Cnd.where("id", "=", recordId));
		return MobileResult.success("SUCCESS", null);
	}

	/**
	 * 删除材料题答案附件
	 */
	public Map<String, Object> deleteFile(@Param("..") final HomeworkDeleteAnswerFileForm form) {
		Integer id = form.getId();
		dbDao.delete(HomeworkQuestionAnswerFileEntity.class, id);
		return MobileResult.success("SUCCESS", null);
	}

	/**
	 * 查询所有答题记录
	 */
	public Map<String, Object> allRecord(final HomeworkEntryForm form) {
		String token = form.getToken();
		Integer userId = RedissionUserCache.getUserId(token);

		Integer homeworkId = form.getHomeworkId();

		List<HomeworkAnswerInfoEntity> data = dbDao.query(HomeworkAnswerInfoEntity.class,
				Cnd.where("studentId", "=", userId).and("taskId", "=", homeworkId), null);
		return MobileResult.success("SUCCESS", data);
	}

	/**
	 * 保存试题作答信息
	 */
	@Aop("txDb")
	public Map<String, Object> saveQuestionAnswer(final HomeworkSaveQuestAnswerForm form) {
		String token = form.getToken();
		Integer userId = RedissionUserCache.getUserId(token);

		Integer questId = form.getQuestId();
		Integer recordId = form.getRecordId();
		if (!Util.isEmpty(recordId)) {
			HomeworkAnswerInfoEntity record = dbDao.fetch(HomeworkAnswerInfoEntity.class,
					Cnd.where("id", "=", recordId));
			if (Util.isEmpty(record)) {
				return MobileResult.error("答题记录不存在", null);
			} else {
				HomeworkQuestionEntity quest = dbDao.fetch(HomeworkQuestionEntity.class, Cnd.where("id", "=", questId));
				if (Util.isEmpty(quest)) {
					return MobileResult.error("试题不存在", null);
				}

				//新增或更新
				HomeworkQuestionAnswerEntity qa = dbDao.fetch(
						HomeworkQuestionAnswerEntity.class,
						Cnd.where("studentId", "=", userId).and("questionId", "=", questId)
								.and("answerId", "=", recordId));

				String answerContent = QuestionUtil.answerNormalize(form.getAnswerContent());
				Integer questionType = quest.getQuestionType();
				if (Util.isEmpty(questionType)) {
					return MobileResult.error("题型不能为空", null);
				} else {
					//填空题的答案保存为整个题干+答案(答案保存在input标签中)
					if (QuestionTypeEnum.FILLIN.intKey() == questionType) {
						String stem = quest.getStem();
						answerContent = QuestionUtil.fillInAnswerContent(stem, answerContent);
					}
				}

				//客观题判卷
				Integer objective = quest.getObjective();
				if (Util.isEmpty(objective)) {
					return MobileResult.error("试题主客观类型不能为空", null);
				}

				//本题得分
				Double actualScore = 0d;
				if (ObjectiveEnum.ObjectiveType.intKey() == quest.getObjective()) {
					String answerOption = quest.getAnswerOption();
					//如果回答正确则更新客观题得分
					if (QuestionUtil.objectiveCorrect(answerOption, answerContent)) {
						actualScore += quest.getScore();
					}
				}

				if (Util.isEmpty(qa)) {
					qa = new HomeworkQuestionAnswerEntity();
					qa.setStudentId(userId);
					qa.setAnswerId(recordId);
					qa.setQuestionId(questId);
					qa.setScore(quest.getScore());
					qa.setHomeworkId(record.getTaskId());
					qa.setAnswerContent(answerContent);
					qa.setActualScore(actualScore);

					qa = dbDao.insert(qa);
				} else {
					Integer anId = qa.getId();
					dbDao.update(HomeworkQuestionAnswerEntity.class,
							Chain.make("answerContent", answerContent).add("actualScore", actualScore),
							Cnd.where("id", "=", anId));
				}

				HomeworkSaveAnswerDto data = new HomeworkSaveAnswerDto();
				BeanUtil.copyProperties(qa, data);
				return MobileResult.success("SUCCESS", data);
			}
		} else {
			return MobileResult.error("答题记录id不能为空", null);
		}
	}

	/**
	 * 提交作业
	 */
	@Aop("txDb")
	public Map<String, Object> commitHomework(final HomeworkCommitForm form) {
		String token = form.getToken();
		Integer userId = RedissionUserCache.getUserId(token);

		Integer recordId = form.getRecordId();
		if (!Util.isEmpty(recordId)) {
			HomeworkAnswerInfoEntity record = dbDao.fetch(HomeworkAnswerInfoEntity.class,
					Cnd.where("id", "=", recordId));
			if (Util.isEmpty(record)) {
				return MobileResult.error("答题记录不存在", null);
			} else {
				Integer status = record.getStatus();
				if (Util.isEmpty(status)) {
					return MobileResult.error("数据错误，答题记录状态不能为空", null);
				} else {
					if (AnswerStatusEnum.finish.intKey() == status || AnswerStatusEnum.marking.intKey() == status) {
						return MobileResult.error("该次练习已交卷，请勿重复提交", null);
					}
				}

				//1,先保存用户的答案
				List<HomeworkAnswerQuestionDto> questList = form.getQuestList();
				if (!Util.isEmpty(questList)) {
					List<HomeworkQuestionAnswerEntity> toBeAdd = new ArrayList<>();
					List<HomeworkQuestionAnswerEntity> toBeUpdate = new ArrayList<>();

					questList.forEach(q -> {
						Integer questId = q.getId();
						Double actualScore = 0d;
						String answerContent = QuestionUtil.answerNormalize(q.getAnswerContent());

						Integer questionType = q.getQuestionType();
						if (QuestionTypeEnum.FILLIN.intKey() == questionType) {
							String stem = QuestionUtil.getStem4Storage(q.getStem());
							answerContent = QuestionUtil.fillInAnswerContent(stem, answerContent);
						}

						if (ObjectiveEnum.ObjectiveType.intKey() == q.getObjective()) {
							String answerOption = q.getAnswerOption();
							if (QuestionUtil.objectiveCorrect(answerOption, answerContent)) {
								actualScore += q.getScore();
							}
						}

						HomeworkQuestionAnswerEntity qa = dbDao.fetch(
								HomeworkQuestionAnswerEntity.class,
								Cnd.where("questionId", "=", questId).and("studentId", "=", userId)
										.and("answerId", "=", recordId));
						if (!Util.isEmpty(qa)) {
							//更新答案和分数
							qa.setAnswerContent(answerContent);
							qa.setActualScore(actualScore);
							toBeUpdate.add(qa);
						} else {
							qa = new HomeworkQuestionAnswerEntity();
							qa.setStudentId(userId);
							qa.setAnswerId(recordId);
							qa.setQuestionId(questId);
							qa.setScore(q.getScore());
							qa.setHomeworkId(record.getTaskId());
							qa.setAnswerContent(answerContent);
							qa.setActualScore(actualScore);
							toBeAdd.add(qa);
						}
					});
					if (!Util.isEmpty(toBeAdd)) {
						dbDao.insert(toBeAdd);
					}

					if (!Util.isEmpty(toBeUpdate)) {
						dbDao.update(toBeUpdate, "answerContent", "actualScore");
					}
				}

				//2 客观题判卷
				objectiveReview(userId, recordId);
			}
		}
		return MobileResult.success("SUCCESS", null);
	}

	/**
	 * 查看提交结果页面
	 */
	public Map<String, Object> result(final HomeworkResultForm form) {
		Integer recordId = form.getRecordId();
		HomeworkAnswerInfoEntity data = dbDao.fetch(HomeworkAnswerInfoEntity.class, Cnd.where("id", "=", recordId));
		return MobileResult.success("SUCCESS", data);

	}

	/**
	 * 材料题文件上传
	 * 上传类型:1 图片 2 文件
	 * @param upType 上传类型
	 * @throws IOException 
	 */
	@Aop("txDb")
	public Map<String, Object> uploadFile(final TempFile tf, final HomeworkAnswerFileForm form, Integer upType)
			throws IOException {

		String fileName = form.getFileName();
		Integer resourceType = null;
		String fileUrl = null;
		if (QuestionUtil.UPLOAD_TYPE_IMG == upType) {
			resourceType = QuestionAnswerResourceTypeEnum.IMG.intKey();
			//图片
			InputStream inputStream = tf.getInputStream();

			//文件后缀
			String suffix = Files.getSuffix(fileName);
			suffix = suffix.substring(1);
			fileUrl = qiniuUploadService.uploadImage(inputStream, suffix, fileName);
		} else if (QuestionUtil.UPLOAD_TYPE_VIDEO == upType) {
			//视频
			resourceType = QuestionAnswerResourceTypeEnum.VIDEO.intKey();
			AliyunVideoDesc vd = new AliyunVideoDesc();

			vd.setTitle(fileName);
			File file = tf.getFile();
			fileUrl = aliyunVideoUploadService.uploadFile(vd, file.getAbsolutePath());
		}

		else if (QuestionUtil.UPLOAD_TYPE_FILE == upType) {
			// TODO 文件+音频(小程序如何做?)
			resourceType = QuestionAnswerResourceTypeEnum.FILE.intKey();
		}

		if (!Util.isEmpty(fileUrl)) {
			String token = form.getToken();
			Integer userId = RedissionUserCache.getUserId(token);

			Integer questionId = form.getQuestionId();
			Integer recordId = form.getRecordId();

			HomeworkQuestionEntity quest = dbDao.fetch(HomeworkQuestionEntity.class, Cnd.where("id", "=", questionId));
			if (Util.isEmpty(quest)) {
				return MobileResult.error("试题不存在", null);
			}

			HomeworkAnswerInfoEntity record = dbDao.fetch(HomeworkAnswerInfoEntity.class,
					Cnd.where("id", "=", recordId));
			if (Util.isEmpty(record)) {
				return MobileResult.error("答题记录不存在", null);
			}

			//如果试题的答案还未保存则新增一条答案
			HomeworkQuestionAnswerEntity qa = dbDao.fetch(
					HomeworkQuestionAnswerEntity.class,
					Cnd.where("studentId", "=", userId).and("questionId", "=", questionId)
							.and("answerId", "=", recordId));
			if (Util.isEmpty(qa)) {
				qa = new HomeworkQuestionAnswerEntity();
				qa.setStudentId(userId);
				qa.setAnswerId(recordId);
				qa.setQuestionId(questionId);
				qa.setScore(quest.getScore());
				qa.setHomeworkId(record.getTaskId());
				qa = dbDao.insert(qa);
			}

			Integer answerId = qa.getId();
			Date now = DateUtil.nowDate();
			HomeworkQuestionAnswerFileEntity af = new HomeworkQuestionAnswerFileEntity();
			af.setAnswerId(answerId);
			af.setCreateDate(now);
			af.setResourceName(fileName);
			af.setResourceValue(fileUrl);
			af.setResourceType(resourceType);
			af = dbDao.insert(af);
			return MobileResult.success("success", af);
		} else {
			return MobileResult.error("上传失败", null);
		}
	}

	//客观题判卷
	@Aop("txDb")
	private void objectiveReview(Integer userId, Integer recordId) {
		//设置客观题分数 并置为阅卷状态
		Sql sql = Sqls.create(sqlManager.get("minapp_homework_objective_review"));
		sql.setParam("objective", ObjectiveEnum.ObjectiveType.intKey());
		sql.setParam("userId", userId);
		sql.setParam("recordId", recordId);
		List<HomeworkObjectiveReviewDto> lst = DbSqlUtil.query(dbDao, HomeworkObjectiveReviewDto.class, sql);

		Double objectScore = 0.0d;
		if (!Util.isEmpty(lst)) {
			for (HomeworkObjectiveReviewDto dto : lst) {
				String answerOption = dto.getAnswerOption();
				String answerContent = dto.getAnswerContent();
				if (QuestionUtil.objectiveCorrect(answerOption, answerContent)) {
					objectScore += dto.getScore();
				}
			}
		}
		dbDao.update(
				HomeworkAnswerInfoEntity.class,
				Chain.make("objectScore", objectScore).add("status", AnswerStatusEnum.finish.intKey())
						.add("finishTime", DateUtil.nowDate()), Cnd.where("id", "=", recordId));
	}
}